<template>
  <div class="layout">
    <el-container>
      <el-header>
        <el-menu
          :default-active="$route.path"
          class="el-menu-demo"
          mode="horizontal"
          router
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item index="/books">图书</el-menu-item>
          
          <div class="flex-grow" />
          
          <el-menu-item v-if="!isAuthenticated" index="/login">登录</el-menu-item>
          <el-menu-item v-if="!isAuthenticated" index="/register">注册</el-menu-item>
          
          <el-sub-menu v-if="isAuthenticated" index="user">
            <template #title>
              <el-avatar :size="32" :src="user?.avatar">
                {{ user?.username?.charAt(0) }}
              </el-avatar>
              {{ user?.username }}
            </template>
            <el-menu-item index="/profile">个人中心</el-menu-item>
            <el-menu-item index="/orders">我的订单</el-menu-item>
            <el-menu-item index="/cart">
              <el-badge :value="cartCount" :hidden="cartCount === 0">
                购物车
              </el-badge>
            </el-menu-item>
            <el-menu-item divided @click="logout">退出登录</el-menu-item>
          </el-sub-menu>
          
          <el-menu-item v-if="isAdmin" index="/admin">管理后台</el-menu-item>
          <el-menu-item v-if="isMerchant" index="/merchant">商家后台</el-menu-item>
        </el-menu>
      </el-header>
      
      <el-main>
        <router-view />
      </el-main>
      
      <el-footer>
        <div class="footer">
          <p>&copy; 2024 在线图书销售系统. All rights reserved.</p>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { storeToRefs } from 'pinia'

const userStore = useUserStore()
const cartStore = useCartStore()

const { user, isAuthenticated, isAdmin, isMerchant } = storeToRefs(userStore)
const { cartCount } = storeToRefs(cartStore)

const logout = () => {
  userStore.logout()
}
</script>

<style scoped>
.layout {
  min-height: 100vh;
}

.flex-grow {
  flex-grow: 1;
}

.footer {
  text-align: center;
  padding: 20px;
  color: #666;
}
</style>
